<template>
	<!-- 大盒子 -->
	<div class="MedicenCata">
		<!--  描述  -->
		<!-- <div class="header"></div> -->
		<!-- 主体内容 -->
		<div class="main">
			<!-- 一般用于左侧树菜单 -->
			<div class="main-left">
				<!-- tree -->
			</div>
			<!-- 一般用于右侧表格 -->
			<div class="main-right">
				<!-- 表格下搜索 下拉 时间选择按钮事件等 -->
				<div class="main-icon">
					<div class="main-icon-a">
						<i class="el-icon-byj"
							style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;background-color: #409EFF;color: #fff;"></i>
						<span style="font-weight:400;margin-left: 12px;">库存预警[西药房]</span>
					</div>
					<!-- btn1 -->
					<div class="main-icon-aa">
						<span>库房名称：</span>
						<el-select v-model="selectedValue" slot="prepend" placeholder="请选择" size="mini">
						      <el-option label="西药库" value="西药库"></el-option>
						</el-select>
					</div>
					<div class="main-icon-b">
						<span style="font-size: 12px;color: #606266;font-weight: bold;">药品类型：</span>
						<el-dropdown @command="handleCommand" trigger="click">
							<span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item :command="v.command" v-for="(v,i) in dropdownMenu" :key="i">{{ v.label }}</el-dropdown-item>
								<el-dropdown-item command="e" divided>全部</el-dropdown-item>
							</el-dropdown-menu>
					    </el-dropdown>
					</div>
					<!-- btn2 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 80px;">药品名称：</span>
						<el-input size="mini" placeholder="编码、名称、拼音简码" suffix-icon="el-icon-key" v-model="searchValue"></el-input>
					</div>
					<!-- btn3 -->
					<div class="main-icon-c">
						<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
					</div>
				</div>
				<!-- 表格主题 -->
				<div class="table">
					<el-table :data="tableData" border highlight-current-row :style="{ width: windowWidth + 'px' }"
					element-loading-text="数据加载中..." v-loading="loading" element-loading-spinner="el-icon-refresh"
					@current-change="handleCurrentTableChange">
					<el-table-column prop="shedId" label="入库库房">
						 <template slot-scope="{ row }">
							<span>{{ shedIdMap[row.shedId] || '未知' }}</span>
						</template>
					</el-table-column>
						<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
						<!-- fixed -->
						<el-table-column fixed="left" label="行号" type="index"></el-table-column>
					</el-table>
				</div>
				<!-- feet -->
				<div class="feet" id="feet">
					<!-- 分页 -->
					<el-pagination
					style="margin: 12px;"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageNum"
					:page-sizes="[20, 50, 100]"
					:page-size="pageSize"
					:total="totalSize"
					layout="total, sizes, prev, pager, next, jumper"
					background
					>
					</el-pagination>
					<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" 
					@click="feetHandClick(i)">{{ v.label }}</el-button>
				</div>
			</div>

		</div>
		<!-- 设置预警数量等Model -->
		<div class="addModel">
			<el-dialog
			  title="库存预警编辑[西药]"
			  :visible.sync="toolDisabled"
			  width="70%"
			  top="88px"
			  :before-close="toolHandleClose">
			  <!-- 表格主题 -->
				<div class="InnerTable">
					<el-table :data="InnerTableData" border highlight-current-row :style="{ width: windowWidth + 'px' }"
					element-loading-text="数据加载中..." v-loading="loading" element-loading-spinner="el-icon-refresh"
					@current-change="handleCurrentTableChange" @row-dblclick="dbclick" :cell-class-name="tableCellClassName" >
					<el-table-column prop="shedId" label="入库库房">
						 <template slot-scope="{ row }">
							<span>{{ shedIdMap[row.shedId] || '未知' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="drugCode" label="药品编码" width="128"></el-table-column>
					<el-table-column prop="drugName" label="药品名称" width="128"></el-table-column>
					<el-table-column prop="drugSpec" label="规格描述" width="228"></el-table-column>
					<el-table-column prop="prodentpName" label="生产厂家" width="188"></el-table-column>
					<el-table-column prop="purcCnt" label="库存数量" width="88"></el-table-column>
					<el-table-column prop="unit" label="药品单位" width="88"></el-table-column>
					<el-table-column prop="cntLow" label="最低库存数量" align='center'>
						<template slot-scope="scope">
							<el-input size="mini"
							  v-model="scope.row.cntLow"
							  :ref="scope.row.index + ',' + scope.column.index"  
							  v-if="scope.row.index + ',' + scope.column.index == currentCell"
							  @blur="hideInput(scope.row)"
							  placeholder="请输入"/>
							<span v-else>{{ scope.row.cntLow }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="cntHigh" label="最高库存数量" align='center'>
						<template slot-scope="scope">
							<el-input size="mini"
							  v-model="scope.row.cntHigh"
							  :ref="scope.row.index + ',' + scope.column.index"  
							  v-if="scope.row.index + ',' + scope.column.index == currentCell"
							  @blur="HighideInput(scope.row)"
							  placeholder="请输入"/>
							<span v-else>{{ scope.row.cntHigh }}</span>
						</template>
					</el-table-column>
						<el-table-column v-for="(col, inx) in InnerTableRows" :key="inx" 
						:type="col.type" :prop="col.prop" :label="col.name">
						</el-table-column>
						<!-- fixed -->
						<el-table-column fixed="left" label="行号" type="index" align='center'></el-table-column>
					</el-table>
				</div>
			  <span slot="footer" class="dialog-footer">
			    <el-button size="mini" @click="toolDisabled = false">取 消</el-button>
			    <el-button size="mini" type="primary" @click="toolDisabled = false">确 定</el-button>
			  </span>
			</el-dialog>
		</div>
		
	</div>
</template>

<script>
	// selfs / js
	// import addForm from './addForm.js' //Form表单
	// import AccType from './AddType.js'
	// 接口
	import { pharmacyAlertList,AddpharmacyAlert,pharmacyAlert } from "@/api/MedicenHouse/Western.js";
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			// MedicenCata
		},
		data() {
			return {
				// 树菜单Props
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				windowWidth:'', //右侧表格动态宽度
				searchValue:'',
				selectedValue:'',
				CatalogueName:'药房申领',
				DropDownedName:'全部',
				iconComes:'el-icon-byj',
				currentCell: null, // 单元格隐藏
				// boolean
				disabled:true,
				toolDisabled:false,
				loading:false,
				// number
				idx: 0,
				pageNum: 1, //当前页currentPage
				pageSize: 8,
				totalSize: 10, //总条数
				/* obj */
				addForm:{}, // form表单 新增 * 
				editForm:{}, // form表单 修改 * 
				// arr
				data: [],
				userInfo: [],
				tableData: [],
				currentTable:[],
				InnerTableData:[],
				TypeOption:[
					{ id:1,label:'西药',value:'西药'},{ id:2,label:'中成药',value:'中成药'},
					{ id:3,label:'卫材',value:'卫材'},{ id:4,label:'血液',value:'血液'},
					{ id:5,label:'疫苗',value:'疫苗'},{ id:9,label:'中药',value:'中药'}
				],
				dropdownMenu:[
					{ id:1,label:'卫材',command:'a'},{ id:2,label:'疫苗',command:'b'},{ id:3,label:'中成药',command:'c'},{ id:4,label:'西药',command:'d'},
				],
				formType:[], // 表单头部内容
				statusOption:[{ id:0,label:'禁用',value:'禁用'},{ id:1,label:'可用',value:'可用'}],
				// title右侧按钮
				headerBtn:[
				 { refesh:"refesh", title:"刷新", type:"", icon:"el-icon-refresh" },
				 { senior:"senior", title:"高级", type:"primary", icon:"" },
				],
				feetBtn:[
				 { refesh:"refesh", label:"设置预警数量", type:"primary", icon:"el-icon-edit" },
				 // { refesh:"refesh", label:"修改", type:"primary", icon:"el-icon-finished" },
				 // { refesh:"refesh", label:"删除", type:"primary", icon:"el-icon-document-checked" },
				 // { refesh:"refesh", label:"查看", type:"primary", icon:"el-icon-sort" },
				 // { refesh:"refesh", label:"打印", type:"primary", icon:"el-icon-printer" },
				 // { refesh:"refesh", label:"导出", type:"primary", icon:"el-icon-finished" },
				 // { refesh:"refesh", label:"关闭", type:"primary", icon:"el-icon-close" },
				 ],
				// title右侧按钮
				tableRows:[
					{ name:"药品编码", prop:"drugCode", type:"" },
					{ name:"药品名称", prop:"drugName", type:"" },{ name:"规格描述", prop:"drugSpec", type:"" },
					{ name:"生产厂家", prop:"prodentpName" },{ name:"库存数量", prop:"purcCnt", type:"" },
					{ name:"药品单位", prop:"unit" },{ name:"最低库存数", prop:"cntLow", type:"" },
					{ name:"最高库存数", prop:"cntHigh", type:"" },{ name:"应补库存数", prop:"repairPurcCnt" },
					{ name:"供货单位", prop:"" },{ name:"药房库存数", prop:"pharmacyCnt", type:"" },
				],
				InnerTableRows:[],
				// 表单验证规则
				addFormRules:{},
				// others
				shedIdMap:{
					1: '西药库',
					2: '中药库',
				},
			};
		},
		mounted() {
			this.loadData();
			this.getForm();
			//获取动态盒子宽度，实时赋值给右侧 => this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
			})
			// 定义数据来源
			// this.formType = AccType.map(function(val) { return val })
		},
		methods: {
			/*
				数据源
			*/
			async loadData(){
				let res = await pharmacyAlertList({
					drugName:this.searchValue,
					pageNum:this.pageNum,
					pageSize:this.pageSize,
				});
				if(res.code === 200){
					this.tableData = res.data
					this.totalSize = res.data.totalSize
				}else{
					this.$message({ type: 'error', message: res.message });
					this.tableData = [];
				}
			},
			async getInnerTableData(){
				let res = await pharmacyAlert({
					drugName:this.searchValue,
					pageNum:this.pageNum,
					pageSize:this.pageSize,
				});
				if(res.code === 200){
					this.InnerTableData = res.data
					this.totalSize = res.data.totalSize
				}else{
					this.$message({ type: 'error', message: res.message });
					this.InnerTableData = [];
				}
			},
			// 挂载或销毁前后重新赋值后端参数
			getForm(){
				// 左侧提交表单
				// this.addForm = addForm.map(v => {return v })[0]; // Form
				// this.editForm = addForm.map(v => {return v })[0]; // Form
				// 解构赋值排除 list 属性 => 弃用
				// this.addHeadrForm = addForm.map(item => { let { list, ...newItem } = item; return newItem })[0];
				// this.$handlePermissions(); // 引入全局自定义封装方法
			},
			/*
				about tree
			*/
			handleNodeClick(data,e) {
				this.CatalogueName = data.title
				this.iconComes = 'el-icon-' + this.makePy(data.label)
				console.log(this.iconComes);
				this.loadData();
			},
			// add
			addSubmit(){

			},
			// editSubmit
			async editSubmit(){
				//触发验证表单
				this.$refs.editForm.validate(async(valid) => {
				  if(valid){
					//验证通过
					console.log(this.editForm);
					let res = await updatedocMark(this.editForm)
					console.log(res);
					if (res.code === 200){
					this.$message({
						message:res.message,
						type:"success"
					});
					this.editDialogVisible = false
					this.loadData(); //更新数据驱动
					}else{
					  // 失败
					  this.$message({ type: 'error', message: 'fail!'});
					}
				}
				});
			},
			
			/*
				about table
			*/
			// 表单头部聚焦事件 => addForm
			async sname(val,i) {
				// val.id = i;
				this.idx = i;
				// i event
				switch (i) {
					// case 1: 
					// 	if(val === 1){
					// 		this.addForm.markUpPric = ''
					// 		console.log(this.formType)
					// 		// this.disabled = true
					// 	}else{
					// 		this.addForm.markUpRate = '1.0'
					// 	}
					// break;
				}
			},
			// db events
			// 给单元格绑定横向和竖向的index，这样就能确定是哪一个单元格
			tableCellClassName({row, column, rowIndex, columnIndex}){
				row.index = rowIndex;
				column.index = columnIndex;
			},
			// 当input失去焦点的时候，隐藏input 最小
			async hideInput(row){
				// 定义纯数字正则（正整数）
				const numberRegex = /^\d+$/;
				if(!numberRegex.test(row.cntLow)){
					this.$message.error('数量格式不正确!');
				}else if(Number(row.cntLow.length > 8)){
					this.$message.error('最低库存数量最大长度单位为8！');
				}else if(Number(row.cntLow) > Number(row.cntHigh)){
					this.$message.error('最低库存数量不能大于最高库存数量！');
				}else{
					this.currentCell = null;
					let res = await AddpharmacyAlert(row);
					if(res.code === 200){
						this.$message.success('设置成功！');
						this.toolDisabled = false;
						this.loadData(); // 更新数据驱动
					}else{
						this.$message.error(res.message);
					}
				}
				// console.log('修改后的行数据:', JSON.parse(JSON.stringify(row)));  // 深拷贝避免响应式引用
			},
			async HighideInput(row){
				console.log(row.cntHigh);
				// 定义纯数字正则（正整数）
				const numberRegex = /^\d+$/;
				if(!numberRegex.test(row.cntHigh)){
					this.$message.error('数量格式不正确');
				}else{
					this.currentCell = null;
				}
				console.log('修改后的行数据:', JSON.parse(JSON.stringify(row)));  // 深拷贝避免响应式引用
			},
			// 获得当前双击的单元格的横竖index，然后拼接成一个唯一字符串用于判断，并赋给currentCell  // 拼接后类似这样："1,0","1,1",
			dbclick(row,column) {
				this.currentCell = row.index + ',' + column.index;
				console.log(column.index);
				// 这里必须要setTimeout，因为在点击的时候，input才刚被v-if显示出来，不然拿不到dom
				setTimeout(() => {
					if(column.index == 8){
						// 双击后自动获得焦点
						console.log(column,'colooiqjwqj');
						this.$refs[row.index + ',' + column.index].focus();
					}else if(column.index == 9){
						// 双击后自动获得焦点
						this.$refs[row.index + ',' + column.index].focus();
					}else{
						this.$message.error('表格中只有最低数量和最高数量允许被修改！')
					}
				})
			},
			// SelectVal to editForm
		    // col 里面包含了表头字段和名称，list 是表格数据
		    columnWidth(col, list) {
				let prop = col.prop,lab = col.lab;
				let width = 20; // 设定一个最小值
				let maxlenStr = ""; // 最长字符串
				for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		        }
		        width = Math.max(width, len(lab), len(maxlenStr));
		        // 表格自带的内边距(20px) 自调
		        return width + 12; // 这里加了 12px
		        function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 8;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 8;
		             // 英文大写字符 8px
		             else if ("A" <= char && char <= "Z") length += 8;
					 // 数字
					 else if (Number.isFinite(Number(char))) length += 8;
		             // 中文字符 28px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 18;
		             // 其他 8px
		             else length += 12;
		           }
		           return length;
		        }
		    },
			// see table
			// 表格底部循环按钮事件
			feetHandClick(v){
				// v event
				switch(v){
					case 0:
					// 打开设置预警数量
						this.toolDisabled = true;
						this.getInnerTableData();
					break;
				}
			},
			// input 
			toolHandleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					done();
				  })
				  .catch(_ => {
					
				  });
			},
			// db events
			// 表格单选
			handleCurrentTableChange(val){
				this.currentTable[0] = val
			},

			// 步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0:
						// 处理索引0的逻辑 => 刷新
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已刷新'})
							this.loading = false;		
						}, 1500)
						break;
					case 1:
						// 处理索引1的逻辑
						this.$confirm('敬请期待')
							.then(_ => {})
							.catch(_ => {});
						break;
				}
			},
			handleCommand(command) {
			  console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  console.log('执行A逻辑');
				  this.DropDownedName = '卫材'
				  break;
				case 'b':
				  // 处理b的逻辑
				  console.log('执行B逻辑');
				  this.DropDownedName = '疫苗'
				  break;
				case 'c':
				  // 处理c的逻辑
				  this.DropDownedName = '中成药'
				  break;
				case 'd':
				  // 处理d的逻辑
				  this.DropDownedName = '西药'
				  break;
				case 'e':
				  // 处理e的逻辑
				  this.DropDownedName = '全部'
				  break; 
				// ... 其他 case
			  }
			},
			// 实时宽度
			updateWindowWidth() {
				this.windowWidth = window.innerWidth - 228;
			},
			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
			},
			
		}
	}
</script>

<style lang="less" scoped>
	// content
	.MedicenCata {
		height: 100%;
		width: 100%;
		// header
		.header {
			display: flex;
			flex-direction: row;
			align-items: center;
			height: 40px;
			background-color: #efefef;
			padding: 4px;

			// justify-content: space-evenly;
			// icon
			.header-icon {
				display: flex;
				align-items: center;
			}
			.feetbtn{
				display: flex;
				justify-content: center;
				margin-left: 12px;
			}
		}

		// main
		.main {
			width: 100%;
			display: flex;
			justify-content: space-between;
			// height: 473px; /* 设置父容器的高度 */
			// overflow-y: auto; /* 当内容超出容器高度时显示垂直滚动条 */
			// left
			.main-left {
				
			}

			// right
			.main-right {
				flex: 4;
				height: 100%;
				// pharmacyAlert
				.addmessagesBox{
					.tabs{
						/deep/ .el-select>.el-input{
							width: 172px;
						}
						/deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
							width: 172px;
						}
						/deep/ .el-form-item__content{
							display: flex;
							
							span{
								font-size: 12px;
							}
						}
						.oneLine{
							width: 524px;
							// background-color: indianred;
						}
					}
					/deep/ .el-dialog__title{
						font-size: 12px;
					}
					/deep/ .el-table{
						font-size: 12px;
					}
				}
				// icon
				.main-icon {
					display: flex;
					align-items: center;
					padding: 12px;
					line-height: 40px;
					.main-icon-a{
					
					}
					.main-icon-aa{
						span{
							font-size: 12px;
							margin-left: 12px;
						}
						/deep/ .el-input--mini .el-input__inner{
							width: 128px;
						}
					}
					.main-icon-b{
						margin-left: 28px;
						/deep/ .el-dropdown{
							font-size: 12px;
							cursor: pointer;
						}
						/deep/ .el-dropdown:hover {
							font-weight: bold;
							color: #66b1ff;
						}
						/deep/ .el-icon--right{
							// background-color: #66b1ff;
						}
						/deep/ .el-popper[x-placement^=bottom]{
							margin-top: 0;
						}
					}
					// c
					.main-icon-c{
						display: flex;
						margin-left: 28px;
						/deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b]{
							width: 80%;
						}
					}
				}
				// table
				/deep/ .el-table .cell{
					font-size: 12px;
					text-align: center;
				}

				/deep/ .el-table td.el-table__cell div :first-child{
					text-align: center;
				}
				/deep/ .el-table td.el-table__cell div{
					text-align: left;
					overflow: hidden;
					white-space: normal;
					word-break: break-all;
				}
				
				.table{
					padding: 8px;
				}
			}
		}
		// addModel
		.addModel{
			margin-left: 12px;
			/deep/ .el-dialog__header{
				padding: 4px;
				line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__headerbtn{
				top: 10px;
			}
			/deep/ .el-dialog__body{
				padding: 10px;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
			/deep/ .el-table .cell{
				font-size: 12px;
			}
			// 表格内层table
			.InnerTable{
				/deep/ .el-table th.el-table__cell{
					font-size: 12px;
				}
			}
		}
		
		// feet
		.feet {
			padding: 12px;
			
		}

	}
</style>